<template>
  <section class="todoapp">
    <todo-header @newList="newList"></todo-header>
    <todo-body :list="renderList"
               @delList="delList"
               @Change="Change"
               @fullAll="fullAll"></todo-body>
    <todo-footer :list="list"
               @delAll="delAll"
               :type="type"
               @changeType="changeType"></todo-footer>
  </section>
</template>

<script>
import todoHeader from "./components/todoHeader.vue"
import todoBody from "./components/todoBody.vue"
import todoFooter from "./components/todoFooter.vue"
export default {
  components: {
    todoHeader,
    todoBody,
    todoFooter
  },
  data () {
    return {
      list:JSON.parse(localStorage.getItem('todoList'))|| [
        { id: 1, name: 1, flag: true },
        { id: 2, name: 2, flag: false },
        { id: 3, name: 3, flag: false }
      ],
      type:'all'
    }
  },
  methods: {
    delList (id) {
      this.list = this.list.filter(item => item.id !== id)
    },
    newList (newName) {
      this.list = [...this.list, {
        id: new Date(), name: newName, flag: false
      }]
    },
    Change(id,flag){
      this.list.find(item => item.id === id).flag = flag
    },
    delAll(){
      this.list=this.list.filter(item=>!item.flag)
    },
    fullAll(flag){
      this.list.forEach(item=>item.flag=flag)
    },
    changeType(value){
      this.type=value
    },
  },
  computed:{
    renderList(){
      switch (this.type) {
        case 'all':
          return this.list
        case 'active':
          return this.list.filter(item=>!item.flag)
        case 'completed':
          return this.list.filter(item=>item.flag)
        default:
          return this.list
      }
    }
  },
  watch:{
    list:{
      deep:true,
      handler(newVal){
        localStorage.setItem('todoList',JSON.stringify(newVal))
      }
    }
  }
}
</script>

<style></style>
